package com.wiserun.RestFul.service;

import com.wiserun.RestFul.mapper.PncsOrganizationMapper;
import com.wiserun.RestFul.mapper.PncsUserOrgMapper;
import com.wiserun.RestFul.model.Organization;
import com.wiserun.RestFul.model.UserOrg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PncsUserOrgService {
    @Autowired
    private PncsUserOrgMapper pncsUserOrgMapper;

    /**
     * 插入最新的数据，如果数据库已经存在该条记录，则覆盖插入
     * @param userOrgs
     * @return sum_add 新增数量总和 sum_update 修改数量总和
     */
    @Transactional(propagation= Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor=Exception.class)
    public synchronized HashMap<String,Integer> addUserOrgs(List<UserOrg> userOrgs){
        int add = 0 ;//新增数量
        int update = 0;//修改数量
        int sum_add = 0;//新增数量总和
        int sum_update = 0;//修改数量总和
        HashMap<String,Integer> counts = new HashMap<>();
        //System.err.println("获取的userorg数据是========="+userOrgs);
        for(UserOrg userOrg:userOrgs){
           //System.err.println("获取的userorg数据是========="+userOrg);
            //检查数据库中是否存在重复数据
            int exist = pncsUserOrgMapper.isExist(userOrg);
            if(exist ==0 ){//不存在重复数据,新增数据
                //System.err.println("新增数据-=============================================================");
                add = pncsUserOrgMapper.addUserOrg(userOrg);//插入新数据
                sum_add += add;
                continue;
            }
            //System.err.println("修改数据-=============================================================");
            update = pncsUserOrgMapper.update(userOrg);//修改重复数据
            sum_update +=update;
        }
        counts.put("sum_add",sum_add);
        counts.put("sum_update",sum_update);
        return  counts;
    }
}
